package com.unicdata.ai.demo_2af.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unicdata.ai.demo_2af.annotation.Log;
import com.unicdata.ai.demo_2af.common.entity.User;
import com.unicdata.ai.demo_2af.common.exception.BusinessException;
import com.unicdata.ai.demo_2af.common.result.Result;
import com.unicdata.ai.demo_2af.common.utils.PasswordUtils;
import com.unicdata.ai.demo_2af.common.vo.LoginRequest;
import com.unicdata.ai.demo_2af.common.vo.PasswordUpdateRequest;
import com.unicdata.ai.demo_2af.common.vo.RegisterRequest;
import com.unicdata.ai.demo_2af.common.vo.RoleAssignRequest;
import com.unicdata.ai.demo_2af.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author lhn
 * @date 2025/06/25 17:05
 * @since 1.0.0
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    @Log("用户登录")
    public Result<Map<String, Object>> login(@RequestBody @Valid LoginRequest loginRequest) {
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        Boolean rememberMe = loginRequest.getRememberMe();

        if (StringUtils.isBlank(username)) {
            throw new BusinessException("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            throw new BusinessException("密码不能为空");
        }

        // 执行登录
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            if (rememberMe != null && rememberMe) {
                token.setRememberMe(true);
            }
            subject.login(token);

            // 登录成功，获取当前登录用户信息
            User loginUser = (User) subject.getPrincipal();

            // 更新最后登录时间
            loginUser.setLastLoginTime(new Date());
            userService.updateById(loginUser);

            // 返回用户基本信息和Token
            Map <String, Object> result = new HashMap <>();
            result.put("userId", loginUser.getId());
            result.put("username", loginUser.getUsername());
            result.put("token", subject.getSession().getId().toString());

            return Result.success(result, "登录成功");
        } catch (AuthenticationException e) {
            throw new BusinessException("登录失败: " + e.getMessage());
        }
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    @Log("用户注册")
    public Result<Void> register(@RequestBody @Valid RegisterRequest registerRequest) {
        String username = registerRequest.getUsername();
        String password = registerRequest.getPassword();
        String email = registerRequest.getEmail();
        String mobile = registerRequest.getMobile();

        if (StringUtils.isBlank(username)) {
            throw new BusinessException("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            throw new BusinessException("密码不能为空");
        }
        // 密码复杂度校验
        if (!PasswordUtils.isComplexEnough(password)) {
            throw new BusinessException("密码不符合安全要求：长度8-16位，包含大小写字母、数字、特殊字符中的至少三种");
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setMobile(mobile);

        // 注册用户
        boolean success = userService.register(user);
        if (success) {
            return Result.success(null, "注册成功");
        } else {
            return Result.error("注册失败");
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    @Log("退出登录")
    public Result<Void> logout() {
        SecurityUtils.getSubject().logout();
        return Result.success(null, "退出成功");
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo() {
        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User) subject.getPrincipal();
        if (loginUser == null) {
            return Result.error("获取用户信息失败", 401);
        }

        // 查询最新用户信息
        User user = userService.getById(loginUser.getId());
        // 清除敏感信息
        user.setPassword(null);
        user.setSalt(null);

        return Result.success(user);
    }

    /**
     * 用户列表查询
     */
    @GetMapping("/list")
    @RequiresPermissions("user:view")
    @Log("查询用户列表")
    public Result<IPage <User>> list(@RequestParam(defaultValue = "1") Integer current,
                                     @RequestParam(defaultValue = "10") Integer size,
                                     @RequestParam(required = false) String username) {
        Page<User> page = new Page <>(current, size);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper <>();

        // 按用户名模糊查询
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like(User::getUsername, username);
        }

        IPage<User> userPage = userService.page(page, queryWrapper);
        // 清除敏感信息
        userPage.getRecords().forEach(user -> {
            user.setPassword(null);
            user.setSalt(null);
        });

        return Result.success(userPage);
    }

    /**
     * 获取用户详情
     */
    @GetMapping("/{userId}")
    @RequiresPermissions("user:view")
    public Result<User> getUser(@PathVariable Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }

        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 清除敏感信息
        user.setPassword(null);
        user.setSalt(null);

        return Result.success(user);
    }

    /**
     * 修改密码
     */
    @PostMapping("/updatePassword")
    @Log("修改密码")
    public Result<Void> updatePassword(@RequestBody @Valid PasswordUpdateRequest request) {
        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User) subject.getPrincipal();
        if (loginUser == null) {
            return Result.error("用户未登录", 401);
        }

        try {
            boolean success = userService.updatePassword(loginUser.getId(),
                    request.getOldPassword(), request.getNewPassword());
            if (success) {
                // 密码修改成功后，需要重新登录
                subject.logout();
                return Result.success(null, "密码修改成功，请重新登录");
            } else {
                return Result.error("密码修改失败");
            }
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分配角色
     */
    @PostMapping("/assignRoles")
    @RequiresPermissions("user:edit")
    @Log("分配用户角色")
    public Result<Void> assignRoles(@RequestBody @Valid RoleAssignRequest request) {
        Long userId = request.getUserId();
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }

        try {
            boolean success = userService.assignRoles(userId, request.getRoleIds());
            if (success) {
                return Result.success(null, "角色分配成功");
            } else {
                return Result.error("角色分配失败");
            }
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 禁用/启用用户
     */
    @PostMapping("/changeStatus/{userId}/{status}")
    @RequiresPermissions("user:edit")
    @Log("修改用户状态")
    public Result<Void> changeStatus(@PathVariable Long userId, @PathVariable Integer status) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (status == null || (status != 0 && status != 1)) {
            throw new BusinessException("状态参数错误");
        }

        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 不能修改管理员账号的状态
        if ("admin".equals(user.getUsername())) {
            return Result.error("不能修改超级管理员状态");
        }

        user.setStatus(status);
        user.setUpdateTime(new Date());
        boolean success = userService.updateById(user);

        if (success) {
            return Result.success(null, "状态修改成功");
        } else {
            return Result.error("状态修改失败");
        }
    }

    /**
     * 解锁用户账号
     */
    @PostMapping("/unlock/{userId}")
    @RequiresPermissions("user:edit")
    @Log("解锁用户账号")
    public Result<Void> unlockUser(@PathVariable Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }

        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        if (user.getIsLocked() == null || user.getIsLocked() != 1) {
            return Result.error("用户账号未锁定");
        }

        user.setIsLocked(0);
        user.setLoginFailCount(0);
        user.setLockedTime(null);
        user.setUpdateTime(new Date());
        boolean success = userService.updateById(user);

        if (success) {
            return Result.success(null, "账号解锁成功");
        } else {
            return Result.error("账号解锁失败");
        }
    }

}